//
//  SSMineViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/6.
//

import UIKit

import SwiftyJSON


class SSMineViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
    public var tableView: UITableView!
    public var mainDatas: Array<Any> = []
    public var imageDatas: Array<Any> = []
    var user: SSUser = SSUser()
    var headerView: SSMineHeaderView = SSMineHeaderView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        title = "设置"
        mainDatas = ["我的地址","我要合作","我的邮箱","兑换优惠券","删除帐户","退出登录"]
        imageDatas = ["mine_address","mine_cooperation","mine_email","mine_coupon","mine_delete","loginout_icon"]
        setupUIs()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        network()
    }
    
    func setupUIs() {
        tableView = UITableView(frame: .zero, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self

        tableView?.separatorStyle = .none
        tableView?.showsVerticalScrollIndicator = false
        tableView?.showsHorizontalScrollIndicator = false
        tableView?.estimatedRowHeight = 100
        
        tableView?.register(UINib(nibName: "SSMineTableViewCell", bundle: Bundle.init(for: SSMineTableViewCell.self)), forCellReuseIdentifier: "SSMineTableViewCell")
        view.addSubview(tableView!)
        
        
        tableView?.snp.makeConstraints{ (make) in
            make.top.equalTo(view.safeAreaInsets.top)
            make.left.equalTo(view.safeAreaInsets.left)
            make.right.equalTo(view.safeAreaInsets.right)
            make.bottom.equalTo(view.safeAreaInsets.bottom)
        }
        
        tableView?.contentInsetAdjustmentBehavior = .automatic
        
    }
        
    //当在controller的viewdidload中使用的时候，因为xib开启了auto layout，设置frame不生效，这是因为viewdidload加载在autolayout之前，导致设置的frame被覆盖了
    override func viewDidLayoutSubviews() {
        let headerView = SSMineHeaderView.headerView()
        headerView.frame = CGRect(x: 10, y: 10, width: UIScreen.main.bounds.size.width - 10, height: 230)
        self.headerView = headerView
        tableView.tableHeaderView = headerView
    }
    
    func rightNav() {
            
        if(user.isEmployee == "0"){
            let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
            btn.setTitle("员工", for: .normal)
            btn.setTitleColor(UIColor.black, for: .normal)
    //        btn.setImage(UIImage(named: "headset_nav"), for: .normal)
            btn .addTarget(self, action: #selector(rightNavAcion), for: .touchUpInside)
            let rightItem = UIBarButtonItem(customView: btn)
            self.navigationItem.rightBarButtonItem = rightItem
        }else{
            self.navigationItem.rightBarButtonItem = nil
        }
            
    }
    
    @objc func rightNavAcion(){
            let vc = SSTargetViewController.init()
            vc.user = user
            navigationController?.pushViewController(vc, animated: true)
        }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mainDatas.count
     }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        if indexPath.row == imageDatas.count - 1 {
//            return 100
//        }
        return 70
    }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "SSMineTableViewCell") as! SSMineTableViewCell
         cell.titleIcon.image = UIImage(named: (imageDatas[indexPath.row] as? String)!)
         cell.titleLab.text = mainDatas[indexPath.row] as? String
//         cell.lineView.isHidden = !(indexPath.row == imageDatas.count - 1)
         return cell
     }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if !kIsLogin {
            kNotifiDefault.post(name: .AppShowLoginController, object: nil)
            return
        }
        print("\(indexPath.row)")
        if indexPath.row == 0 {
            let vc = SSAddressListController.init()
            navigationController?.pushViewController(vc, animated: true)
        }else if(indexPath.row == 1){
            let vc = SScooperateViewController.init()
            navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.row == 2 {
            let sb = UIStoryboard(name: "SSSetupMineInfoViewController", bundle: nil)
            let vc = sb.instantiateInitialViewController() as! SSSetupMineInfoViewController
            vc.user = self.user
            navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.row == 3 {
            let vc = SSUserRedeemController.init()
            navigationController?.pushViewController(vc, animated: true)
        }else if indexPath.row == 4 {
            logOff()
        }
        else if indexPath.row == 5 {
            loginOut()
        }
    }
    
    

}


extension SSMineViewController {
    
    func network() {
        var param = [
                    "phoneNo": kUserPhone
        ] as [String:AnyObject]
        if !kIsLogin{
            param = [
                        "phoneNo": ""
            ] as [String:AnyObject]
        }
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getUser_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let data = json["data"].dictionary
                let user = SSUser()
                user.email = data?["email"]?.stringValue ?? ""
                user.phoneNo = data?["phoneNo"]?.stringValue ?? ""
                user.userName = data?["userName"]?.stringValue ?? ""
                user.isEmployee = data?["isEmployee"]?.stringValue ?? ""
                
//                user.phoneNo = data!["phoneNo"]!.stringValue
//                user.userName = data!["userName"]!.stringValue
                self.user = user
                self.headerView.setData(user: user)
                self.setupData()
//                self.rightNav()
                self.tableView.reloadData()
            }
        }
    }
    
    func userLogOff()  {
        
        let param = [
                    "phoneNo": kUserPhone
        ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.userLogOff_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            let json = JSON(parseJSON: result!)
            let retCode = json["retCode"].stringValue
            let retMsg = json["retMsg"].stringValue
            if(retCode == "0000"){
                removeAllData()
                self.view.makeToast("帐户已删除")
                self.headerView.setData(user: SSUser())
                self.setupData()
                self.tableView.reloadData()
            }else{
                dissmissToTast(msg: retMsg)
            }

        }
    }
    
    func setupData() {
        if kIsLogin && mainDatas.count < 6 {
            mainDatas.append("删除帐户")
            mainDatas.append("退出登录")
            imageDatas.append("mine_delete")
            imageDatas.append("loginout_icon")
        }else if (!kIsLogin && mainDatas.count > 4){
            mainDatas.removeLast()
            mainDatas.removeLast()
            imageDatas.removeLast()
            imageDatas.removeLast()
        }
    }
    
    func logOff()  {
        let alertView = EtcAlertView(title:"是否删除帐号" ,message: "帐户删除后该帐户的所有数据将永久删且无法找回！！！", cancleTitle:"取消", confirmTitle: "确定")
        alertView.showAlert(confirm:  {
            self.userLogOff()
        }) {
        }
    }
    
}



func loginOut(text:String = "是否要退出登录") {
    let alertView = EtcAlertView(message: text, cancleTitle:"取消", confirmTitle: "确定")
    alertView.showAlert(confirm:  {
        removeAllData()
        kNotifiDefault.post(name: .AppShowLoginController, object: nil)
    }) {
    }
}
